package org.syyo.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.syyo.admin.common.constant.PageConstant;
import org.syyo.admin.common.enums.ResultEnum;
import org.syyo.admin.common.exception.SysException;
import org.syyo.admin.domain.ResultVo;
import org.syyo.admin.domain.request.UserReq;
import org.syyo.admin.domain.response.MenuResp;
import org.syyo.admin.domain.response.RoleResp;
import org.syyo.admin.domain.response.UserResp;
import org.syyo.admin.mapper.UserMapper;
import org.syyo.admin.mapper.UserRoleMapper;
import org.syyo.admin.service.UserService;
import org.syyo.admin.utils.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: wangzhong
 * @Date: 2019/10/8 17:06
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private PageConstant pageConstant;
    /**
     * 添加用户
     * @param req
     * @return
     */
    @Override
    @Transactional
    public ResultVo addUser(UserReq req) {
        CheckUtils.validate(req);
        //校验用户表的账号
        int count = userMapper.checkUser(req.getAccountId());
        if (count != 0) {
            throw new SysException(ResultEnum.USER_EXIST.getCode(), ResultEnum.USER_EXIST.getMessage());
        }

        // 密码加密
        String passWord = req.getPassWord();
        String passwordMd5 = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(passWord.getBytes()).getBytes());
        req.setPassWord(passwordMd5);

        Date date = DateUtils.getDate();
        //添加创建时间
        req.setCreateDate(date);
        req.setStatus(1);
        //添加用户表
        int i = userMapper.addUser(req);
        if (i != 1) {
            throw new SysException(ResultEnum.USER_ADD_FAIL.getCode(), ResultEnum.USER_ADD_FAIL.getMessage());
        }

        Integer userId = req.getUserId();
        //添加相应的角色
        List<Integer> rids = req.getRoleIdList();
        if (rids != null && rids.size() > 0) {
            for (Integer rid : rids) {
                int k = userRoleMapper.addUserRole(userId, rid);
                if (k != 1) {
                    throw new SysException(ResultEnum.USER_ADD_FAIL.getCode(), ResultEnum.USER_ADD_FAIL.getMessage());
                }
            }
        }
//        return i;
        return ResultUtils.response(i);
    }

    /**
     * 删除用户
     *
     * @param req
     * @return
     */
    @Override
    @Transactional
    public ResultVo delUser(UserReq req) {
        Integer userId = req.getUserId();
        //判断用户id是否存在
        UserResp user = userMapper.getUser(userId);
        if (user == null) {
            throw new SysException(ResultEnum.ROLE_NOT_EXIST.getCode(), ResultEnum.ROLE_NOT_EXIST.getMessage());
        }
        int i = userMapper.delUser(userId);
        if (i != 1) {
            throw new SysException(ResultEnum.USER_DEL_FAIL.getCode(), ResultEnum.USER_DEL_FAIL.getMessage());
        }
        //删除用户对应角色
        userRoleMapper.delUserRoleByUserId(userId);

        return ResultUtils.response(i);
    }

    /**
     * 修改用户
     *
     * @param req
     * @return
     */
    @Override
    @Transactional
    public ResultVo editUser(UserReq req) {
        //判断用户id是否存在
        UserResp userResp = userMapper.getUser(req.getUserId());
        if (userResp == null) {
            throw new SysException(ResultEnum.USER_NOT_EXIST.getCode(), ResultEnum.USER_NOT_EXIST.getMessage());
        }

        //添加更新时间
        Date date = DateUtils.getDate();
        req.setUpdateDate(date);
        int i = userMapper.editUser(req);
        if (i != 1) {
            throw new SysException(ResultEnum.USER_UPDATE_FAIL.getCode(), ResultEnum.USER_UPDATE_FAIL.getMessage());
        }
        //处理角色
        List<Integer> rids = req.getRoleIdList();
        if (rids != null && rids.size() > 0) {
            Integer userId = req.getUserId();
            userRoleMapper.delUserRoleByUserId(userId);
            for (Integer rid : rids) {
                int k = userRoleMapper.addUserRole(userId, rid);
                if (k != 1) {
                    throw new SysException(ResultEnum.USER_UPDATE_FAIL.getCode(), ResultEnum.USER_UPDATE_FAIL.getMessage());
                }
            }
        }

        return ResultUtils.response(i);
    }

    /**
     * 查询用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public ResultVo getUser(Integer userId) {
        UserResp user = userMapper.getUser(userId);
        List<RoleResp> roles = user.getRoles();
        if (MyListUtils.isNotEmpty(roles)) {
            //封装用户角色id
            List<Integer> list = new ArrayList<>();
            for (RoleResp role : roles) {
                list.add(role.getRoleId());
            }
            user.setRoleIdList(list);
        }
        return ResultUtils.response(user);
    }

    /**
     * 查询用户列表
     *
     * @param req
     * @return
     */
    @Override
    public ResultVo listUser(UserReq req) {
        Integer pageNum = req.getPageNum();
        Integer pageSize = req.getPageSize();
        if(pageNum == null ){
            pageNum = pageConstant.getPageNum();
        }
        if(pageSize == null || pageSize > pageConstant.getPageRange() ){
            pageSize = pageConstant.getPageSize();
        }
        //分页处理
        PageHelper.startPage(pageNum,pageSize);
        List<UserResp> userResps = userMapper.listUser(req);
        PageInfo<UserResp> list = new PageInfo<>(userResps);

        return ResultUtils.response(list);
    }

    /**
     * 登录
     *
     * @param req
     * @return
     */
    @Override
    public ResultVo login(UserReq req) {
        String accountId = req.getAccountId();
        UserResp userResp = userMapper.login(accountId);
        //判断用户是否存在
        if (userResp == null) {
            throw new SysException(ResultEnum.USER_OR_PASSWORD_ERROR.getCode(), ResultEnum.USER_OR_PASSWORD_ERROR.getMessage());
        }
        Integer status = userResp.getStatus();
        //判断用户状态是否禁用
        if (status == null) {
            throw new SysException(ResultEnum.ACCOUNT_NOT_ACTIVATE.getCode(), ResultEnum.ACCOUNT_NOT_ACTIVATE.getMessage());
        }
        //判断用户状态是否禁用
        if (status == 0) {
            throw new SysException(ResultEnum.ACCOUNT_NOT_ACTIVATE.getCode(), ResultEnum.ACCOUNT_NOT_ACTIVATE.getMessage());
        }

        String passWordDb = userResp.getPassWord();
        String passWord = req.getPassWord();
        //双重加密
        String passWordMd5 = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(passWord.getBytes()).getBytes());
        if (!passWordDb.equals(passWordMd5)) {
            throw new SysException(ResultEnum.USER_OR_PASSWORD_ERROR.getCode(), ResultEnum.USER_OR_PASSWORD_ERROR.getMessage());
        }
        // 生成token
        Date date = DateUtils.getDate();
        long time = date.getTime();
        String timeStamp = userResp.getAccountId() + userResp.getUserId() + time;
        String token = DigestUtils.md5DigestAsHex(timeStamp.getBytes());
        //更新token
        userResp.setToken(token);
        userMapper.updateToken(accountId, token);

        return ResultUtils.response(userResp);
    }

    /**
     * 根据用户id获取用户当前权限
     *
     * @param
     * @return
     */
    @Override
    public  ResultVo getShowMenuByToken(String token) {
        List<MenuResp> menus = userMapper.getShowMenuByToken(token);
        //权限封装成树形结构
        List<MenuResp> menuResps = TreeUtils.listToMenuTree(menus);

        return ResultUtils.response(menuResps);
    }

    @Override
    public Object appLogout(UserReq req) {
        //todo 退出
        return null;
    }

    @Override
    @Transactional
    public ResultVo pwd(UserReq req) {
        String accountId = req.getAccountId();
        String oldPassWord = req.getPassWord();//旧密码
        String newPassWord = req.getNewPassWord();//新密码
        UserResp userResp = userMapper.login(accountId);
        String passWord = userResp.getPassWord();//数据库密码

        String oldPassWordMd5 = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(oldPassWord.getBytes()).getBytes());

        if (!oldPassWordMd5.equals(passWord)) {
            throw new SysException(ResultEnum.USER_OR_PASSWORD_ERROR.getCode(), ResultEnum.USER_OR_PASSWORD_ERROR.getMessage());
        }
        String newPassWordMd5 = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(newPassWord.getBytes()).getBytes());
        int i = userMapper.updatePwd(accountId, newPassWordMd5);
        if (i == 0) {
            throw new SysException(ResultEnum.USER_DEL_FAIL.getCode(), ResultEnum.USER_DEL_FAIL.getMessage());
        }

        return ResultUtils.response(i);
    }

    @Override
    public ResultVo logout(UserReq req) {
        return ResultUtils.response(null);
    }


}
